package com.jczy.cyclone.widget.photoview

import android.content.ContentResolver
import android.content.ContentValues
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2

import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.fenghongzhang.lib_net.model.Image
import com.fenghongzhang.module_main.R
import com.fenghongzhang.module_main.databinding.FragmentPhotoViewerBinding
import com.fenghongzhang.module_main.glide.pic.Info
import com.fenghongzhang.module_main.glide.pic.PhotoView
import com.gyf.immersionbar.ImmersionBar

import java.io.File
import java.io.FileOutputStream

/**
 *@author Wcj
 *@description
 *@date 2022/7/5 16:11
 */
class PhotoViewerDialog(
    //图片，包含缩略图和原图链接
    private val mPicList: List<Image>,
    //图片位置信息
    private val mImageInfo: List<Info>?,
    //默认显示的位置
    private val startPosition: Int = 0,
    private val onClose: ((pos: Int) -> Unit)? = null
) : DialogFragment() {
    constructor( //原图片的链接
        picUrls: List<String>,
        //图片信息
        mImageInfo: List<Info>?,
        //默认显示的位置
        startPosition: Int = 0,
        //避免签名和主构造方法签名相同
        unused: Int = 0,
        onClose: ((pos: Int) -> Unit)? = null
    ) : this(picUrls.map { Image(url = it) }, mImageInfo, startPosition, onClose)

    private lateinit var mBinding: FragmentPhotoViewerBinding
    private lateinit var mPhotoViewPagerAdapter: PhotoViewPagerAdapter

    //第一进入
    private var mEntered = false

    //当前显示Position
    private var mCurrentPosition: Int = 0

    /*
        <style name="DialogFullScreen" parent="Theme.AppCompat.Dialog">
            <item name="android:windowIsFloating">false</item>
            <item name="android:windowNoTitle">true</item>
            <item name="android:background">@android:color/transparent</item>
            <item name="android:windowBackground">@android:color/transparent</item>
            <item name="android:windowFullscreen">true</item>
            <item name="android:colorBackgroundCacheHint">@null</item>
        </style>
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_FRAME, R.style.DialogFullScreen)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_photo_viewer, container, false)
        if (dialog != null && mImageInfo == null) {
            dialog!!.window?.setWindowAnimations(R.style.FadeAnim)
        }
        mBinding = FragmentPhotoViewerBinding.inflate(inflater)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //拦截返回按键
        dialog!!.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
                exit()
                return@setOnKeyListener true
            }

            keyCode == KeyEvent.KEYCODE_BACK
        }
        //沉浸状态栏
        ImmersionBar.with(this).init()
        //初始item不为0的处理，如果startPosition,会出现没有动画的问题
//        mPhotoViewPagerAdapter = if (startPosition != 0) {
//            PhotoViewPagerAdapter(listOf(mPicList[startPosition]), if (mImageInfo?.get(startPosition) == null) null else listOf(mImageInfo[startPosition]), onImageClick = {
//                exit()
//            }, onImageLongClick = {
//                showSavePicDialog(it)
//            })
//        } else {
//            PhotoViewPagerAdapter(mPicList, mImageInfo, onImageClick = {
//                exit()
//            }, onImageLongClick = {
//                showSavePicDialog(it)
//            })
//        }
        mPhotoViewPagerAdapter = PhotoViewPagerAdapter(mPicList, mImageInfo, onImageClick = {
            exit()
        }, onImageLongClick = {
            showSavePicDialog(it)
        })


        mBinding.vp.adapter = mPhotoViewPagerAdapter
        mBinding.vp.setCurrentItem(startPosition, false)
        mBinding.tvIndicator.text = String.format(" %d/%d", startPosition + 1, mPicList.size)
        mCurrentPosition = startPosition

        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position == 0 && !mEntered) {
                    mEntered = true
                    show()
                } else {
                    mBinding.tvIndicator.text = String.format(" %d/%d", position + 1, mPicList.size)
                }
                mCurrentPosition = position
            }
        })


    }

    //退出
    private fun exit() {
        runCatching {
            val photoView = (mBinding.vp.getChildAt(0) as RecyclerView)
                .layoutManager?.findViewByPosition(mCurrentPosition)?.findViewById<PhotoView>(R.id.pv)

            if (mImageInfo.isNullOrEmpty() || photoView?.drawable == null) {
                mPhotoViewPagerAdapter.cancelLoadImage(true)
                dismissAllowingStateLoss()
                return
            }
            photoView.animaTo(mImageInfo.getOrNull(mCurrentPosition) ?: mImageInfo.last()) {
                onClose?.invoke(mCurrentPosition)
                mPhotoViewPagerAdapter.cancelLoadImage(true)
                dismissAllowingStateLoss()
            }
        }
    }

    //显示
    private fun show() {
        val photoView = (mBinding.vp.getChildAt(0) as RecyclerView)
            .layoutManager?.findViewByPosition(0)?.findViewById<PhotoView>(R.id.pv)
        photoView?.animaDuring = 300
//        mImageInfo?.apply {
//            photoView?.animaFrom(this[startPosition])
//        }
        //设置新的Adapter
//        if (startPosition != 0) {
//            photoView?.postDelayed({
//                mPhotoViewPagerAdapter = PhotoViewPagerAdapter(mPicList, mImageInfo, false, onImageClick = {
//                    exit()
//                }, onImageLongClick = {
//                    showSavePicDialog(it)
//                })
//                mBinding.vp.adapter = mPhotoViewPagerAdapter
//                mBinding.vp.setCurrentItem(startPosition, false)
//                mPhotoViewPagerAdapter.notifyDataSetChanged()
//            }, 300)
//        }
    }

    fun showDialog(manager: FragmentManager) {
        super.show(manager, this::class.java.simpleName)
    }

    private fun showSavePicDialog(position: Int) {
        runCatching {
//            MoreActionDialog(getString(R.string.string_save_pic)) {
//                //处理权限
//                handleRequestPermissions(*getStorageCompatPermission(),
//                    desc = "保存图片到相册需要授予文件的读写权限",
//                    onGranted = {
//                        savePic(position)
//                    },
//                    onDenied = {
//                        ToastUtils.showShort(context, getString(R.string.string_save_failed))
//                    })
//            }.show(childFragmentManager, MoreActionDialog.TAG)
        }
    }

    /**
     * 下载图片
     */
    private fun savePic(position: Int) {
//        GlideApp.with(this).downloadOnly().load(AliOssUrl(mPicList[position].url)).listener(object : RequestListener<File> {
//            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>?, isFirstResource: Boolean): Boolean {
//                ToastUtils.showShort(requireContext(), getString(R.string.string_save_failed))
//                return false
//            }
//
//            override fun onResourceReady(
//                resource: File?,
//                model: Any?,
//                target: Target<File>?,
//                dataSource: DataSource?,
//                isFirstResource: Boolean
//            ): Boolean {
//                if (resource == null) {
//                    ToastUtils.showShort(requireContext(), getString(R.string.string_save_failed))
//                    return false
//                }
//                copyFileToGallery(resource, "content_${System.currentTimeMillis()}.jpg")
//                ToastUtils.showShort(requireContext(), getString(R.string.string_save_success))
//                return false
//            }
//        }).preload()
    }

    fun copyFileToGallery(file: File, fileName: String) {
        val resolver: ContentResolver = requireActivity().contentResolver
        val values = ContentValues()
        val uriSavedFile: Uri? = if (Build.VERSION.SDK_INT >= 29) {
            if (fileName.uppercase().contains("JPG")) {
                values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
                values.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis())
                values.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "Pictures/Cyclone")
                values.put(MediaStore.Files.FileColumns.IS_PENDING, true)
                values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.Files.FileColumns.MIME_TYPE, "image")
                resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
                values.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis())
                values.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "Movies/Cyclone")
                values.put(MediaStore.Files.FileColumns.IS_PENDING, true)
                values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.Files.FileColumns.MIME_TYPE, "video")
                resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
            }
        } else {
            values.put(MediaStore.Files.FileColumns.TITLE, fileName)
            values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, fileName)
            values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
            if (fileName.uppercase().contains("JPG")) {
                values.put(MediaStore.Files.FileColumns.MIME_TYPE, "image")
                resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                values.put(MediaStore.Files.FileColumns.MIME_TYPE, "video")
                resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
            }

        }
        uriSavedFile?.apply {
            val pfd = resolver.openFileDescriptor(this, "w") as ParcelFileDescriptor
            pfd.use {
                file.inputStream().use { input ->
                    FileOutputStream(pfd.fileDescriptor).use { output ->
                        input.copyTo(output, DEFAULT_BUFFER_SIZE)
                    }
                }
            }
            if (Build.VERSION.SDK_INT >= 29) {
                values.clear()
                values.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
                resolver.update(this, values, null, null)
            }
        }

    }
}

